<template>
  <CommonPage>
    <template #action>
      <NButton type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增菜单
      </NButton>
    </template>

    <AppCard bordered bg="#fafafc dark:black" class="mb-30 min-h-60 rounded-4">
      <form class="flex justify-between p-16" @submit.prevent="handleSearch()">
        <n-scrollbar x-scrollable>
          <n-space :size="[32, 16]" class="p-10">
            <MeQueryItem label="菜单名" :label-width="50">
              <n-input v-model:value="queryItems.name" type="text" placeholder="请输入菜单名" clearable />
            </MeQueryItem>
            <MeQueryItem label="状态" :label-width="50">
              <n-select v-model:value="queryItems.status" clearable :options="DATA_STATUS" />
            </MeQueryItem>
          </n-space>
        </n-scrollbar>
        <div class="flex-shrink-0 p-10">
          <NButton ghost type="primary" @click="handleReset">
            <i class="i-fe:rotate-ccw mr-4" />
            重置
          </NButton>
          <NButton attr-type="submit" class="ml-20" type="primary">
            <i class="i-fe:search mr-4" />
            搜索
          </NButton>
        </div>
      </form>
    </AppCard>

    <NDataTable
      :loading="loading"
      :scroll-x="1200"
      :row-key="(row) => row.id"
      :columns="columns"
      :data="tableData"
    />
    <MenuAddAndEdit ref="modalRef" :menus="permissionTree" @refresh="handleSearch()" />
  </CommonPage>
</template>

<script setup>
import { AppCard, CommonPage, MeQueryItem } from '@/components'
import { NButton, NTag } from 'naive-ui'
import { useTemplateRef } from 'vue'
import api from './api'
import MenuAddAndEdit from './components/MenuAddAndEdit.vue'

defineOptions({ name: 'MenuList' })

// 状态字典-> 数据状态
const { DATA_STATUS } = $dict('DATA_STATUS')

/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  handleSearch()
})

const tableData = ref([])
const loading = ref(false)

const columns = [
  { title: '菜单名称', key: 'name' },
  {
    title: '图标',
    key: 'icon',
    width: 150,
    render(row) {
      return h('div', { class: `${row.icon} text-16` })
    },
  },
  { title: '排序', key: 'order_num' },
  { title: '权限标识', key: 'perms' },
  { title: '路由地址', key: 'path' },
  {
    title: '状态',
    key: 'status',
    render: row =>
      h(
        NTag,
        {
          size: 'small',
          bordered: false,
          type: row.status === '0' ? 'success' : 'error',
        },
        {
          default: () => row.status === '0' ? '启用' : '停用',
        },
      ),
  },
  { title: '创建时间', key: 'created_at' },
  {
    title: '操作',
    key: 'actions',
    width: 320,
    align: 'right',
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            onClick: () => handleAdd(row),
          },
          {
            default: () => '新增',
            icon: () => h('i', { class: 'i-fe:plus text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

function handleSearch() {
  loading.value = true
  api.read({ ...queryItems.value }).then(({ data = [] }) => (tableData.value = buildTree(data))).finally(() => loading.value = false)
}

function handleReset() {
  queryItems.value = { name: null, status: null }
  handleSearch()
}

const modalRef = useTemplateRef('modalRef')

function handleAdd(item = {}) {
  modalRef.value?.handleOpen({
    action: 'add',
    title: `新增菜单 - ${item.name ? item.name : '顶级'}`,
    row: { parent_id: item.id || 0 },
    okText: '保存',
  })
}

function handleEdit(item = {}) {
  modalRef.value?.handleOpen({
    action: 'edit',
    title: `编辑菜单 - ${item.name}`,
    row: item,
    okText: '保存',
  })
}

function handleDelete(item = {}) {
  const d = $dialog.warning({
    content: `确定删除《${item.name}》？`,
    title: '提示',
    positiveText: '确定',
    negativeText: '取消',
    async onPositiveClick() {
      try {
        d.loading = true
        const { message } = await api.delete({ id: item.id.toString() })
        $message.success(message)
        handleSearch()
      }
      finally {
        d.loading = false
      }
    },
  })
}

function buildTree(array) {
  const map = new Map()
  const tree = []

  // 将数组转换为 map 方便查找
  array.forEach((item) => {
    map.set(item.id, item)
  })

  array.forEach((item) => {
    const parent = map.get(item.parentID)
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    }
    else {
      tree.push(item)
    }
  })

  return tree
}

const permissionTree = ref([])
api.getAllPermissionTree().then(({ data = [] }) => (permissionTree.value = data))
</script>
